from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.shortcuts import redirect,render
from django.http import JsonResponse


class UserInfo:
    def __init__(self, role,name,id):
        self.role = role
        self.name = name
        self.id = id
        self.menu_name = None
        self.text_list = []

class AuthMiddleware(MiddlewareMixin):
    def is_white_url(self,request):
        if request.path_info in settings.WHITE_URL:
            return True

    def process_request(self,request):
        if self.is_white_url(request):
            return

        # 登录验证
        user_dict = request.session.get(settings.FC_SESSION)

        if not user_dict:
            return redirect('login')

        request.fc_user = UserInfo(**user_dict)

    def process_view(self, request, view_func, view_args, view_kwargs):
        if request.path_info in settings.WHITE_URL:
            return

        current_name = request.resolver_match.url_name

        if current_name in settings.FC_PERMISSION_PUBLIC:
            return
        user_permission_dict = settings.FC_PERMISSION[request.fc_user.role]

        if current_name not in user_permission_dict:
            is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
            if is_ajax:
                return JsonResponse({'status': False,'detail':"无权访问"})
            else:
                render(request,'permission.html')
        text_list = []
        menu_name = user_permission_dict[current_name]['text']
        text_list.append(menu_name)

        menu_name = current_name
        while user_permission_dict[menu_name]['parent']:
            menu_name = user_permission_dict[current_name]['parent']
            text_list.append(user_permission_dict[menu_name]['text'])

        text_list.append('首页')
        text_list.reverse()

        request.fc_user.menu_name = menu_name
        request.fc_user.text_list = text_list